package com.heima.ssm.controller;

import com.heima.ssm.pojo.Permission;
import com.heima.ssm.pojo.Role;
import com.heima.ssm.pojo.UserInfo;
import com.heima.ssm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author Penguin
 * @create Date 2021/5/6  Time 19:34
 */

@Controller
@RequestMapping("role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @RequestMapping("findAll")
    public ModelAndView findAll(){
        ModelAndView mv = new ModelAndView();
        List<Role> roleList = roleService.findAll();
        mv.addObject("roleList",roleList);
        mv.setViewName("role-list");
        return mv;
    }

    @RequestMapping("save")
    public String add(Role role){
        roleService.add(role);
        return "redirect:findAll";
    }

    //20210507
    @RequestMapping("findById")
    public ModelAndView findById(@RequestParam(name = "id",required = true)int roleId){
        ModelAndView mv = new ModelAndView();
        Role roleInfo = roleService.findById(roleId);
        mv.addObject("role",roleInfo);
        mv.setViewName("role-show");
        return mv;
    }

    //给角色添加权限
    @RequestMapping("findRoleByIdAndAllPermission")
    public ModelAndView findRoleByIdAndAllPermission(@RequestParam(name = "id",required = true)int roleId){
        ModelAndView mv = new ModelAndView();
        //1.选中要添加权限的角色，将该角色id往后端传
        Role role = roleService.findById(roleId);
        //2.查出角色可以添加的权限，即角色当前没有的权限。通过roleId查询可以添加的权限
        List<Permission> permissions = roleService.findOtherPermissionByRoleId(roleId);

        mv.addObject("role",role);
        mv.addObject("permissionList",permissions);
        mv.setViewName("role-permission-add");
        return mv;
    }

    @RequestMapping("addPermissionToRole")
    public String addPermissionToRole(@RequestParam(name = "roleId",required = true) int roleId,
                                      @RequestParam(name = "ids",required = true) int[] permissionIds){

        roleService.addPermissionToRole(roleId,permissionIds);
        return "redirect:findAll";
    }
}
